#!/bin/bash
set -e  # 启用错误检测
MODULE=$PROJECT_NAME
VERSION_TIME=$VERSION_TIME
VERSION_GIT=$VERSION_GIT
PROFILES_ACTIVE=$PROFILES_ACTIVE
PORT_HOST=$PORT_HOST
PORT_CONT=$PORT_CONT
VERSION=$PROFILES_ACTIVE-$VERSION_TIME-$VERSION_GIT
DIST=dist.tar.gz

DIR=~/projects/$MODULE
echo '================================'
echo `date +%Y%m%d' '%H:%M:%S`
echo '================================'
echo "PORT: "$PORT
echo "MODULE: "$MODULE
echo "VERSION_TIME: "$VERSION_TIME
echo "VERSION_GIT: "$VERSION_GIT
echo "PROFILES_ACTIVE: "$PROFILES_ACTIVE
echo "VERSION: "$VERSION

if [ -z "$MODULE" ]; then
    echo "MODULE is empty. Exiting."
    exit 1
fi

# 检查文件夹是否存在
cd $DIR
echo 'pwd: '$(pwd)

# 检查文件是否存在
if [ ! -f "$DIST" ]; then
    echo "错误：文件 '$DIST' 不存在！"
    exit 1  # 终止脚本并返回状态码 1
fi

# 如果文件存在，可以继续执行其他命令
echo "文件 '$DIST' 存在，继续执行..."
tar xzf $DIST

if [ -n "$MODULE" ]; then
    docker stop $(docker ps -a --filter "name=$MODULE" --format "{{.ID}}") || true
    docker rm $(docker ps -a --filter "name=$MODULE" --format "{{.ID}}") || true
    docker rmi -f $(docker images | grep $MODULE | awk '{print $3}') || true
    echo "==> stop and rm container successfully"
else
    echo 'MODULE为空'
fi

docker build --progress=plain -f Dockerfile -t $MODULE:$VERSION .
echo "==> build Dockerfile successfully"

docker run --dns=8.8.8.8 -itd --privileged=true --name $MODULE -p $PORT_HOST:$PORT_CONT $MODULE:$VERSION
echo "==> docker run successfully"

